<!-- 点击帖子的人员信息，弹出人员的基本信息 -->
<template>
  <div   class="user-profile-view">
      
   

  <div class="profile-container">
    <div class="profile-header">
      <div class="header-content">
        <el-avatar :size="140" :src="user.avatar" />
        <div class="profile-info">
          <div class="name-row">
            <h2>{{ user.username }}</h2>
            <el-tag v-if="user.gender === '男'" type="primary" size="small" class="gender-tag">
              <el-icon><Male /></el-icon> 男
            </el-tag>
            <el-tag v-else-if="user.gender === '女'" type="danger" size="small" class="gender-tag">
              <el-icon><Female /></el-icon> 女
            </el-tag>
          </div>
          
          <div class="id-row">
            <span>小红书号：{{ user.redid }}</span>
            <span class="ip-location">IP属地：{{ user.location }}</span>
          </div>
          
          <div class="bio-tag">
            <span>{{ user.bio }}</span>
          </div>
          
          <div class="stats">
            <div class="stat-item" @click="showFollowingDialog1(user.id)">
              <span class="stat-value">{{ user.following }}</span>
              <span class="stat-label">关注</span>
            </div>
            <div class="stat-item" @click="showFollowersDialog1(user.id)">
              <span class="stat-value">{{ user.followers }}</span>
              <span class="stat-label">粉丝</span>
            </div>
            <div class="stat-item" @click="showNotesDialog1(user.id)">
              <span class="stat-value">{{ user.notes }}</span>
              <span class="stat-label">笔记</span>
            </div>
            <div class="stat-item" @click="showLikesDialog1(user.id)">
              <span class="stat-value">{{ user.likes }}</span>
              <span class="stat-label">获赞</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="tabs-container">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="我的笔记" name="notes"></el-tab-pane>
        <el-tab-pane label="点赞" name="likes"></el-tab-pane>
        <el-tab-pane label="收藏" name="collections"></el-tab-pane>
      </el-tabs>
    </div>

    <div class="profile-content">
      <!-- 我的笔记 -->
      <div v-if="activeTab === 'notes'" class="notes-grid">
        <div v-for="note in notes" :key="note.id" class="note-item" >
            <div class="note-image">
             <img :src="note.image" alt="加载失败" @click="showNoteDetailDialog(note)" />
          </div>
          
          <div class="note-content">
            <h3 class="note-title">{{ note.title }}</h3>
            <p class="note-desc">{{ note.description }}  
                    <el-tag 
                        v-for="(tag, index) in note.tags" 
                        :key="index" 
                        size="small" 
                        class="content-tag"
                        style="margin-left: 3px;"
                    >
                        {{ tag }}
                    </el-tag>
            </p>
          </div>
          
          <div class="note-footer">
            
              <div class="user-info">
                <el-avatar :size="24" :src="note.avatar" />
                <span class="username">{{ note.name }}</span>
              </div>
              
              <div class="like-action" @click.stop="toggleLike(note)">
                <el-icon :class="{'liked': note.isliked}">
                  <Star />
                </el-icon>
                <span class="like-count">{{ note.likes }}</span>
              </div>
             
          </div>
        </div>
      </div>

      <!-- 点赞的笔记 -->
      <div v-else-if="activeTab === 'likes'" class="notes-grid">
        <div v-for="note in likedNotes" :key="note.id" class="note-item"  >
            <div class="note-image">
             <img :src="note.image" alt="加载失败" @click="showNoteDetailDialog(note)" />
          </div>
          
            <div class="note-content">
                <h3 class="note-title">{{ note.title }}</h3>
                <p class="note-desc">{{ note.description }}  
                        <el-tag 
                            v-for="(tag, index) in note.tags" 
                            :key="index" 
                            size="small" 
                            class="content-tag"
                            style="margin-left: 3px;"
                        >
                            {{ tag }}
                        </el-tag>
                </p>
            </div>
          
          <div class="note-footer">
        
              <div class="user-info">
                <el-avatar :size="24" :src="note.avatar" />
                <span class="username">{{ note.name }}</span>
              </div>
              
              <div class="like-action" @click.stop="toggleLike(note)">
                <el-icon :class="{'liked': note.isliked}">
                  <Star />
                </el-icon>
                <span class="like-count">{{ note.likes }}</span>
              </div>
            
          </div>
        </div>
      </div>

      <!-- 收藏的笔记 -->
      <div v-else-if="activeTab === 'collections'" class="notes-grid">
        <div v-for="note in collectedNotes" :key="note.id" class="note-item"  >
            <div class="note-image">
             <img :src="note.image" alt="加载失败" @click="showNoteDetailDialog(note)" />
          </div>
          
          <div class="note-content">
            <h3 class="note-title">{{ note.title }}</h3>
            <p class="note-desc">{{ note.description }}  
                    <el-tag 
                        v-for="(tag, index) in note.tags" 
                        :key="index" 
                        size="small" 
                        class="content-tag"
                        style="margin-left: 3px;"
                    >
                        {{ tag }}
                    </el-tag>
            </p>
          </div>
          
          <div class="note-footer">
             
              <div class="user-info">
                <el-avatar :size="24" :src="note.avatar" />
                <span class="username">{{ note.name }}</span>
              </div>
              
              <div class="like-action" @click.stop="toggleLike(note)">
                <el-icon :class="{'liked': note.isliked}">
                  <Star />
                </el-icon>
                <span class="like-count">{{ note.likes }}</span>
              </div>
            
          </div>
        </div>
      </div>
    </div>

    <!-- 关注列表弹窗 -->
    <el-dialog v-model="showFollowingDialog" title="关注列表" width="50%">
      <div class="user-list">
        <div v-for="user in followingList" :key="user.id" class="user-item">
          <el-avatar :size="50" :src="user.avatar" />
          <div class="user-infoo">
            <span class="username">{{ user.name }}</span>
            <span class="bio">{{ user.bio }}</span>
          </div>
          <el-button 
            v-if="!user.isFollowing" 
            type="danger" 
            size="small"
            @click="followUser(user)"
          >
            关注
          </el-button>
          <el-button 
            v-else 
            type="info" 
            size="small"
            @click="unfollowUser(user)"
          >
            已关注
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 粉丝列表弹窗 -->
    <el-dialog v-model="showFollowersDialog" title="粉丝列表" width="50%">
      <div class="user-list">
        <div v-for="user in followersList" :key="user.id" class="user-item">
          <el-avatar :size="50" :src="user.avatar" />
          <div class="user-infoo">
            <span class="username">{{ user.name }}</span>
            <span class="bio">{{ user.bio }}</span>
          </div>
          <el-button 
            v-if="!user.isFollowing" 
            type="danger" 
            size="small"
            @click="followUser(user)"
          >
            回关
          </el-button>
          <el-button 
            v-else 
            type="info" 
            size="small"
            @click="unfollowUser(user)"
          >
            互相关注
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 笔记列表弹窗 -->
    <el-dialog v-model="showNotesDialog" title="笔记列表" width="70%">
      <div class="notes-list">
        <div v-for="note in allNotes" :key="note.id" class="note-list-item">
          <img :src="note.image" alt="note image" class="note-thumbnail" />
          <div class="note-info">
            <h4>{{ note.title }}</h4>
            <p>{{ note.description }}</p>
            <div class="note-stats">
              <span><el-icon><Star /></el-icon> {{ note.likes }}</span>
            </div>
          </div>
          <div class="note-actions">
            <el-button size="small" @click="editNote(note)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteNote(note)">删除</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 获赞列表弹窗 -->
    <el-dialog v-model="showLikesDialog" title="获赞列表" width="50%">
      <div class="likes-list">
        <div v-for="like in likesList" :key="like.id" class="like-item">
          <el-avatar :size="50" :src="like.avatar" />
          <div class="like-info">
            <span class="username">{{ like.name }}</span>
            <span class="action">赞了你的{{like.type}}</span>
            <span class="note-title">{{ like.noteTitle }}</span>
          </div>
          <span class="time">{{ formatTime(like.time) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>

 <!-- 帖子详情弹窗 -->
 <el-dialog
      v-model="showNoteDetail"
      :fullscreen="isMobile"
      :show-close="false"
      custom-class="note-detail-dialog"
      @close="closeDetail"
    >
      <div class="note-detail-container">
        <!-- 左侧图片区域 - 全屏无间距 -->
        <div class="detail-left">
          <div class="image-container">
            <img :src="currentNote.images[currentImageIndex]" alt="note image" />
            <div v-if="currentNote.images.length > 1" class="side-nav-arrows">
              <div class="nav-arrow left" @click.stop="prevImage">
                <el-icon><ArrowLeft /></el-icon>
              </div>
              <div class="nav-arrow right" @click.stop="nextImage">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            <div v-if="currentNote.images.length > 1" class="dot-indicators">
              <div
                v-for="(img, index) in currentNote.images"
                :key="index"
                class="dot"
                :class="{ active: currentImageIndex === index }"
                @click.stop="currentImageIndex = index"
              ></div>
            </div>
          </div>
        </div>

        <!-- 右侧内容区域 - 可滚动 -->
        <div class="detail-right">
          <div class="scroll-content">
            <!-- 用户信息区域 -->
            <div class="user-info">
              <el-avatar :size="50" :src="currentNote.avatar" />
              <div class="user-meta">
                <span class="username">{{ currentNote.name }}</span>
                <span class="follow-count">{{ currentNote.followers }} 粉丝</span>
              </div>
              <el-button
                v-if="!currentNote.isFollowing"
                type="danger"
                round
                class="follow-btn"
                @click="followAuthor"
              >
                关注
              </el-button>
              <el-button
                v-else
                type="info"
                round
                class="follow-btn"
                @click="followAuthor"
              >
                已关注
              </el-button>
            </div>

            <el-divider />

            <!-- 帖子内容 -->
            <div class="note-content">
              <h2>{{ currentNote.title }}</h2>
              <p>{{ currentNote.content }}</p>
            </div>

            <el-divider />

            <!-- 评论区 -->
            <div class="comments-section">
              <h3>评论 ({{ currentNote.comments.length }})</h3>
              <div class="comment-list">
                <!-- 遍历嵌套评论 -->
                <template v-for="comment in nestedComments" :key="comment.id"  >
                  <!-- 渲染当前评论 -->
                 <div class="comment-item-xian">
                  

                  <div
                    class="comment-item"
                    :style="{ 'margin-left': comment.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="40" :src="comment.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ comment.username }}</span>
                        <span class="comment-time">{{ formatTime(comment.createtime) }}</span>
                      </div>
                      <p class="comment-text">{{ comment.content }}</p>
                      <div v-if="comment.images" class="comment-images">
                        <img
                          v-for="(img, idx) in comment.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(comment)">
                          <el-icon :class="['icon', { 'dianzan': comment.isdianzan }]"><Star /></el-icon> {{ comment.likes }}
                        </span>
                        <span @click="replyToComment(comment)">回复</span>
                      </div>
                    </div>
                  </div>

                  <!-- 递归渲染子评论 -->
                  <template v-if="comment.replies && comment.replies.length">
                  <div
                    v-for="reply in comment.replies"
                    :key="reply.id"
                    class="comment-item"
                    :style="{ 'margin-left': reply.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="30" :src="reply.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ reply.username }}</span>
                        <span class="comment-time">{{ formatTime(reply.createtime) }}</span>
                      </div>
                      <p class="comment-text">
                        <template v-if="reply.replyusername">
                          <span class="reply-mention">回复 @{{ reply.replyusername }} : </span>
                        </template>
                        {{ reply.content }}
                      </p>
                      <div v-if="reply.images" class="comment-images">
                        <img
                          v-for="(img, idx) in reply.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(reply)">
                          <el-icon :class="['icon', { 'dianzan': reply.isdianzan }]"><Star /></el-icon> {{ reply.likes }}
                        </span>
                        <span @click="replyToComment(reply)">回复</span>
                      </div>
                    </div>
                  </div>
                </template>
                </div>
                </template>
              </div>
            </div>
          </div>
          <!-- 固定评论框 -->
          <div class="fixed-comment-input">
            <!-- 回复用户信息显示（当有回复对象时显示） -->
            <div v-if="replyingTo" class="reply-info">
              <span>回复 @{{ replyingTo.username }}</span>
              <el-icon class="close-reply" @click="cancelReply"><Close /></el-icon>
            </div>

            <!-- 正常模式（未聚焦输入框时） -->
            <div v-if="!isInputFocused" class="comment-normal-mode">
              <!-- 左侧输入框 -->
              <el-input
                v-model="newComment"
                placeholder="写下你的评论..."
                class="comment-input"
                @focus="handleInputFocus"
              />
              
              <!-- 右侧操作按钮 -->
              <div class="action-buttons">
                <div class="action-item" @click="toggleLikeNote">
                  <el-icon :class="['icon', { 'liked': currentNote.isliked }]"><Star /></el-icon>
                  <span>{{ currentNote.likes }}</span>
                </div>
                
                <div class="action-item" @click="toggleFavorite">
                  <el-icon :class="['icon', { 'favorited': currentNote.isFavorited }]"><Collection /></el-icon>
                  <span>{{ currentNote.collectioncount }}</span>
                </div>
                
                <div class="action-item" @click="handleInputFocus">
                  <el-icon class="icon"><ChatDotRound /></el-icon>
                  <span>{{ currentNote.comments.length }}</span>
                </div>
                
                <div class="action-item" @click="shareNote">
                  <el-icon class="icon"><Share /></el-icon>
                  <span>分享</span>
                </div>
              </div>
            </div>

            <!-- 编辑模式（聚焦输入框时） -->
            <div v-else class="comment-edit-mode">
              <!-- 文本输入区（可自动扩展高度） -->
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="textAreaRows"
                placeholder="写下你的评论..."
                class="comment-textarea"
                @input="adjustTextareaHeight"
              />
              
              <!-- 底部操作栏 -->
              <div class="edit-actions">
                <!-- 左侧功能按钮 -->
                <div class="left-actions">
                  <el-icon class="action-icon" @click="insertMention"><User /></el-icon>
                  <!-- 表情包预留位置 -->
                  <el-icon class="action-icon" @click="showEmojiPicker"><HelpFilled /></el-icon>
                  <el-icon class="action-icon" @click="showFavoriteEmojis"><Star /></el-icon>
                  <el-icon class="action-icon" @click="uploadImage">
                    <input 
                      type="file" 
                      ref="imageInput" 
                      accept="image/*" 
                      style="display: none" 
                      @change="handleImageUpload"
                    />
                    <Picture />
                  </el-icon>
                </div>
                
                <!-- 右侧操作按钮 -->
                <div class="right-actions">
                  <el-button class="cancel-btn" @click="cancelComment">取消</el-button>
                  <el-button 
                    class="send-btn" 
                    type="danger" 
                    :disabled="!newComment.trim()"
                    @click="submitComment(currentNote.id)"
                  >
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </el-dialog>

  </div>

</template>

<script setup>
import { ref, reactive,computed } from 'vue'
import NoteDetailDialog from './NoteDetailDialog.vue'
import request from '../utils/request';
import { 
  View as xin, 
  ChatDotRound, 
  Star, ArrowLeft, ArrowRight,HelpFilled,
  Male, 
  Female,
  Picture
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineProps,onMounted } from 'vue';
import { useUserStore } from '../utils/userStore'
const loading = ref(true)

const userStore = useUserStore()
// 2. 创建响应式 users
const users = ref([])
// 3. 定义获取用户数据的函数
const fetchUsers = () => {
  
  const user = userStore.getUser
  users.value = user
  console.log(users.value)
}

onMounted(async () => {
  debugger;
  try {
    loading.value = true
    // ...你的逻辑
    fetchUsers() ;
    showUserProfilePage();
    getMainList(); // 加载页面帖子信息
  } finally {
    loading.value = false
  }
})

const showUserProfilePage = async() => {
  try {
    debugger;
    const response = await request.post('/sys/user/getUserId', {"id": users.value.id})
    user.value = {
      ...user.value, // 保留默认值
      ...response.data // 覆盖为API数据
    }
  } catch (error) {
    console.error('获取用户数据失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

  const getMainList = async () => { 
    From.value.userId =users.value.id;  //userId 用于子查询点赞表
    loading.value = true
    try {
      
      From.value.userid =users.value.id;
      const main = await request.post('/xhs/main/getMainList', From.value)
      notes.value = main.data.records.map(note => ({
        ...note,
        isliked: note.isliked === 0 ? false : true,// 是否关注
        tags: parseTags(note.tags) // 确保 tags 是数组
      }));

      From.value.targettype='1';
      From.value.otheruser ='sign';
      From.value.userid ='';
      From.value.targetid =user.value.id;  //userId 用于查询条件，代替userid 
      const main2 = await request.post('/xhs/main/getMainList', From.value)
      debugger;
      likedNotes.value = main2.data.records.map(note => ({
        ...note,
        isliked: note.isliked === 0 ? false : true,// 是否关注
        tags: parseTags(note.tags) // 确保 tags 是数组
      }));
      debugger;
      From.value.targettype='3';
      From.value.otheruser ='sign';
      const main3 = await request.post('/xhs/main/getMainList', From.value)
      collectedNotes.value = main3.data.records.map(note => ({
        ...note,
        isliked: note.isliked === 0 ? false : true,// 是否关注
        tags: parseTags(note.tags) // 确保 tags 是数组
      }));

      ElMessage.success('查询成功')
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error(`查询失败: ${error.message}`)
    } finally {
      loading.value = false
    }
  }

  const parseTags = (tags) => {
    try {
      if (!tags) return [];
      return typeof tags === 'string' ? JSON.parse(tags) : tags;
    } catch (e) {
      return [];
    }
  };

const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + currentNote.value.images.length) % currentNote.value.images.length
}

const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % currentNote.value.images.length
}


const activeTab = ref('notes')
const currentImageIndex = ref(0)
  // 评论相关
const isInputFocused = ref(false)
const textAreaRows = ref(1)
const replyingTo = ref(null)
const imageInput = ref(null)

const newComment = ref('')
const isMobile = ref(false)

debugger;
// 获取用户数据
//  const props  = defineProps({
//   user: {
//     type: Object,
//     required: true
//   }
// })

const user = ref({
  avatar: '', // 默认值
  username: '',
  gender: '',
  redid: '',
  location: '',
  bio: '',
  following: 0,
  followers: 0,
  notes: 0,
  likes: 0
})
 

// 新增状态管理
const showNoteDetail = ref(false)
const currentNote = ref({
  id: null,
  images: [],
  author: {
    id: null,
    name: '',
    avatar: '',
    isFollowing: false,
    followers: 0
  },
  title: '',
  content: '',
  tags: [],
  comments: []
})

const showNoteDetailDialog = async (note) => {
  
  // 转换数据格式
  const fatieid = note.userid;  // 发帖人的id
  const userId = users.value.id //当前登录用户的id
debugger;
  const res = await request.post('/xhs/main/getMainList', {"id":note.id,"targettype":"1","userId":userId,"fatieid":fatieid})
  const main = res.data.records[0];
  const images = parseTags(main.imagesort)
  const talk = await request.post('/xhs/talk/getByContentid', {"contentid":main.id,"targettype":"2","userId":users.value.id})
  currentNote.value = {
    ...main,
    id: main.id,
    //images: [note.image], // 将单图片转为数组
    images: images, // 将单图片转为数组
    name: main.username,
    avatar: main.avatar,
    isFollowing: main.isFollowing === 0 ? false : true,// 是否关注
    followers: main.followers,   // 粉丝数量
    followListId: main.followListId,  // 关注表id
    content: main.description,
    collectioncount:main.collectioncount,
    comments: generateComments(talk)
  }
  currentImageIndex.value = 0
  showNoteDetail.value = true
}

// 生成评论数据结构
const generateComments =  (talk) => {
  
  const comments = []
  for (let i = 0; i < talk.data.length; i++) {
    comments.push({
      id: talk.data[i].id,
      isdianzan: talk.data[i].isdianzan === 0 ? false : true,// 是否点赞
      userid: talk.data[i].userid,
      contentid: talk.data[i].contentid,//
      username:  talk.data[i].username,
      avatar: talk.data[i].avatar,
      content: talk.data[i].content,
      createtime: talk.data[i].createtime,
      likes: talk.data[i].likes,
      depth:talk.data[i].depth,
      parentid:talk.data[i].parentid,
      images: talk.data[i].imageid ? [talk.data[i].imageid] : undefined
    })
  }
  return comments
}

// 计算嵌套评论结构
const nestedComments = computed(() => {
  const comments = currentNote.value.comments || [];
  // 获取一级评论 (depth=0)
  const topLevelComments = comments.filter(c => c.depth === 0);
  // 为每个一级评论添加 replies 属性
  return topLevelComments.map(comment => ({
    ...comment,
    replies: getReplies(comments, comment.id)
  }));
});

// 递归获取子评论
const getReplies = (comments, parentId) => {
  const replies = comments.filter(c => c.parentid === parentId);
  return replies.map(reply => ({
    ...reply,
    replies: getReplies(comments, reply.id) // 递归获取子评论
  }));
};

// 帖子点赞，后台修改数据
const followList = ref({
  userid: '', 
  followerid: '', 
  relationtype: '', 
  followername: '',  
  followeravatar:'',
  isliked:null,
  followListId:'',// 关注信息id 
})

  // 帖子点赞，后台修改数据
  const dz_Like = ref({
  id: '', 
  likes: '', 
  userid: '', 
  targettype: 1, //目标类型(1-帖子 2-评论 3-收藏 )
  likes:null,
  isliked:null,
  collectioncount:null,
  talkid:'',
})

// 关注作者
const followAuthor = async() => {
  currentNote.value.isFollowing = !currentNote.value.isFollowing
  followList.value.userid = users.value.id, //当前用户id
  followList.value.followerid = currentNote.value.userid, //当前帖子用户id
  followList.value.relationtype = 1,  // 关系类型(1-普通粉丝,2-铁粉,3-好友,4-拉黑)
  followList.value.followername = currentNote.value.username,
  followList.value.followeravatar = currentNote.value.avatar,
  followList.value.isliked = currentNote.value.isFollowing  //关注或者取消 
  followList.value.followListId = currentNote.value.followListId // 关注信息id,用于删除
  const main = await request.post('/xhs/followinglist/addOrDeletFollow', followList.value)
}

// 评论点赞功能实现
const likeComment = async(comment) => {
      const aa = comment ;
      //findIndex 查找数组中是否有相同 id 的 comment。如果找到（index !== -1），就用新 comment 替换旧的,如果没找到（index === -1），就用 unshift 把新 comment 插入到数组开头。
      comment.isdianzan = !comment.isdianzan
      comment.likes += comment.isdianzan ? 1 : -1

      dz_Like.value.id = comment.contentid,  //帖子id
      dz_Like.value.talkid = comment.id,    // 评论id 
      dz_Like.value.commentcount = comment.likes // 评论数
      dz_Like.value.userid =users.value.id  //  
      dz_Like.value.targettype = 2   //目标类型(1-帖子 2-评论  3-收藏)
      dz_Like.value.isliked = comment.isdianzan  //点赞或取消点赞
      const main = await request.post('/xhs/main/updateMain', dz_Like.value)

      const index = currentNote.value.comments.findIndex(c => c.id === comment.id);
    if (index !== -1) {
      currentNote.value.comments[index] = comment; // 替换匹配到的 comment
    } else {
      currentNote.value.comments.unshift(comment); // 如果没有匹配到，就插入到开头
    }
}

// 回复评论
const replyToComment = (comment) => {
  
  replyingTo.value = {
    id: comment.id, //评论id
    depth: comment.depth, // 是否一级评论，0是，1否
    parentid: comment.parentid, //一级评论id
    userid: comment.userid,
    username: comment.username
  }
  isInputFocused.value = true
}


// 取消回复
const cancelReply = () => {
  replyingTo.value = null
}

// 取消评论
const cancelComment = () => {
  isInputFocused.value = false
  newComment.value = ''
  replyingTo.value = null
  textAreaRows.value = 1
}

// 提交评论
const submitComment = async (id) => {
  if (newComment.value.trim()) {
    const commentData = ref({
      userid: '1', // 替换为实际的用户 ID
      content: newComment.value,
      contentid:id,
      createtime: new Date(),
      likes: 0,
      depth: replyingTo.value ? 1 : 0,
      parentid: replyingTo.value  ? (replyingTo.value.depth === 1 ? replyingTo.value.parentid : replyingTo.value.id) : null,
      replyuserid: replyingTo.value === null ? null: replyingTo.value.userid ,   
      replyusername: replyingTo.value  === null ? null: replyingTo.value.username,
      imageid:''
    })
    const res = await request.post('/xhs/talk/saveTalk', commentData.value)
    currentNote.value.comments = res.data;
    cancelComment()
  }

}


// 处理输入框聚焦
const handleInputFocus = () => {
  isInputFocused.value = true
}

// 调整文本框高度
const adjustTextareaHeight = () => {
  const lineCount = (newComment.value.match(/\n/g) || []).length + 1
  textAreaRows.value = Math.min(Math.max(lineCount, 1), 4)
}

// 分享笔记
const shareNote = () => {
  // 分享功能实现
  console.log('分享笔记')
}

// 插入@提及
const insertMention = () => {
  newComment.value += '@'
}

// 显示表情选择器
const showEmojiPicker = () => {
  // 显示表情选择器逻辑
  console.log('显示表情选择器')
}

// 显示收藏表情
const showFavoriteEmojis = () => {
  // 显示收藏表情逻辑
  console.log('显示收藏表情')
}

// 上传图片
const uploadImage = () => {
  imageInput.value.click()
}

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 处理图片上传逻辑
    console.log('上传图片:', file.name)
  }
}

// 处理笔记详情弹窗关闭
const handleNoteDetailClose = () => {
  showNoteDetail.value = false
  currentNote.value = null
}

// 处理关注作者
const handleFollowAuthor = async (author) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    author.isFollowing = true
    ElMessage.success(`已关注 ${author.name}`)
  } catch (error) {
    ElMessage.error('关注失败')
  }
}

// 处理提交评论
const handleSubmitComment = async ({ content, noteId }) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('评论成功')
    // 刷新评论列表
    currentNote.value.comments.unshift({
      id: Date.now(),
      author: user.value,
      content,
      time: new Date(),
      likes: 0,
      level: 0
    })
  } catch (error) {
    ElMessage.error('评论失败')
  }
}

// 处理点赞评论
const handleLikeComment = async (commentId) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    const comment = currentNote.value.comments.find(c => c.id === commentId)
    if (comment) {
      comment.likes++
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    ElMessage.error('点赞失败')
  }
}

// 处理回复评论
const handleReplyComment = (comment) => {
  ElMessage.info(`回复 ${comment.author.name}: ${comment.content}`)
  // 实际可以自动填充回复框
}

const notes = ref([])

const From = ref({
    userId: '', // 当前用户ID
    userid: '', // 目标用户ID
    targetid:'',/// 目标ID
    targettype:'', // 目标类型(1-帖子 2-评论 3-收藏)
    otheruser: '',
    page: '1',
    size: '20'
})

// 用户数据
const myNotes = ref([])

// 点赞的笔记
const likedNotes = ref([])

// 收藏的笔记
const collectedNotes = ref([])

// 弹窗控制状态
const showFollowingDialog = ref(false)
const showFollowersDialog = ref(false)
const showNotesDialog = ref(false)
const showLikesDialog = ref(false)



// 模拟数据
const followingList = ref([])
const followersList = ref([])
const allNotes = ref([])
const likesList = ref([])
 
// 显示关注列表
const showFollowingDialog1 = async(id) => {
  debugger;
  const user = await request.post('/sys/user/getFollowing',{'id':id} );
  followingList.value = user.data.map(user => ({
    id: user.id,
    name: user.username,
    avatar: user.avatar,
    bio: user.bio,
    isFollowing: true
  }))
  showFollowingDialog.value = true
}

// 显示粉丝列表
const showFollowersDialog1 = async (id) => {
  const user = await request.post('/sys/user/getFollowers',{'id':id} );
  followersList.value = user.data.map(user => ({
    id: user.id,
    name: user.username,
    avatar: user.avatar,
    bio: user.bio,
    isFollowing: user.isFollowing
  }))
  showFollowersDialog.value = true
}

// 显示笔记列表
const showNotesDialog1 =async (id) => {
  debugger;
  const user = await request.post('/sys/user/getMain',{'id':id} );
  allNotes.value = user.data.map(note => ({
    id: note.id,
    image: note.image,
    title: note.title,
    description: note.description,
    views: note.viewcount,
    comments: note.collectioncount,
    likes: note.likes,
    time: note.createtime
  }))
  showNotesDialog.value = true
}

// 显示获赞列表
const showLikesDialog1 = async(id) => {
  debugger;
  const user = await request.post('/sys/user/getLikes',{'id':id} );
  likesList.value = user.data.map(like => ({
    id: like.id,
    name: like.username,
    avatar: like.avatar,
    noteTitle: like.title,
    time: like.createtime,
    type: like.type,

  }))
  showLikesDialog.value = true
}

// 关注用户
const followUser = (user) => {
  user.isFollowing = true
  ElMessage.success(`已关注 ${user.name}`)
}

// 取消关注
const unfollowUser = (user) => {
  user.isFollowing = false
  ElMessage.warning(`已取消关注 ${user.name}`)
}

// 编辑笔记
const editNote = (note) => {
  ElMessage.info(`编辑笔记: ${note.title}`)
}

// 删除笔记
const deleteNote = (note) => {
  ElMessageBox.confirm(`确定要删除笔记《${note.title}》吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = allNotes.value.findIndex(n => n.id === note.id)
    if (index !== -1) {
      allNotes.value.splice(index, 1)
      user.value.notes--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 格式化时间
const formatTime = (time) => {
  const now = new Date()
  const diff = now - new Date(time)
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return new Date(time).toLocaleDateString()
  }
}

// 主页面点赞/取消点赞
const toggleLike =  async(note) => {
  const user = userStore.getUser // 获取用户信息
  
  note.isliked = !note.isliked
  note.likes += note.isliked ? 1 : -1
  dz_Like.value.id = note.id,
  dz_Like.value.likes = note.likes
  dz_Like.value.userid = users.value.id  // 当前登录用户id 暂写死 待修改
  dz_Like.value.targettype = 1
  dz_Like.value.isliked = note.isliked
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
  getMainList();
}

// 详情页面 点赞笔记
const toggleLikeNote =async () => {
  
  currentNote.value.isliked = !currentNote.value.isliked
  currentNote.value.likes += currentNote.value.isliked ? 1 : -1

  dz_Like.value.id = currentNote.value.id,
  dz_Like.value.likes = currentNote.value.likes
  dz_Like.value.userid =users.value.id  // 当前登录用户id 暂写死 待修改
  dz_Like.value.targettype = 1
  dz_Like.value.isliked = currentNote.value.isliked
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
  getMainList();
}

// 收藏笔记
const toggleFavorite =async () => {
  currentNote.value.isFavorited = !currentNote.value.isFavorited
  currentNote.value.collectioncount += currentNote.value.isFavorited ? 1 : -1

  dz_Like.value.id = currentNote.value.id,
  dz_Like.value.collectioncount = currentNote.value.collectioncount // 收藏数
  dz_Like.value.userid =users.value.id  //  
  dz_Like.value.targettype = 3   //目标类型(1-帖子 2-评论  3-收藏)
  dz_Like.value.isliked = currentNote.value.isFavorited  //
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
  getMainList();
}

// 标签页切换
const handleTabClick = (tab) => {
  console.log('切换到标签:', tab.props.name)
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 100%;
  margin: 0 auto;
  background-color: #f5f5f5;
}

.user-profile-view {
  width: 100%;
}

.profile-header {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

 
.header-content {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 40px; /* 头像和信息之间的间距 */
  max-width: 1200px; /* 限制最大宽度 */
  width: 40%;
}

.profile-info {
  flex: 1;
}

.name-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.name-row h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.gender-tag {
  margin-left: 10px;
}

.id-row {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.ip-location {
  color: #999;
}

.bio-tag {
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.stats {
  display: flex;
  gap: 30px;
  margin-top: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-item:hover {
  transform: scale(1.05);
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.tabs-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tabs-container :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.tabs-container :deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
  height: 50px;
  line-height: 50px;
}

.tabs-container :deep(.el-tabs__item:hover) {
  color: #ff2442;
}

.tabs-container :deep(.el-tabs__item.is-active) {
  color: #ff2442;
  font-weight: 600;
}

.tabs-container :deep(.el-tabs__active-bar) {
  background-color: #ff2442;
  height: 3px;
}

.profile-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.note-item {
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.note-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-container {
  position: relative;
  width: 100%;
  aspect-ratio: 1/1;
  background-color: #f5f5f5;
}

.note-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #ccc;
}

.image-error .el-icon {
  font-size: 40px;
}

.note-content {
  padding: 5px 5px 0 5px;
  flex: 1;
}

.note-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.note-desc {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.note-tags {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.content-tag {
  background-color: #f5f5f5;
  border: none;
  color: #666;
  font-size: 12px;
  height: 24px;
  line-height: 22px;
}
 

  /* 新增样式 */
  .note-footer {
  display: flex;
  justify-content: space-between;
  margin-left: 10px;

  /* border-top: 1px solid #f0f0f0; */
}
 
.user-info .username {
  font-size: 12px;
  color: #666;
}

 

.like-action:hover {
  background-color: #fff0f0;
}

.like-count {
  font-size: 12px;
  color: #666;
}

/* 弹窗样式 */
.user-list {
  max-height: 60vh;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

 
 /* 用户信息 */
 .user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  margin-bottom: 15px;
}

.user-infoo {
  flex: 1;
  margin-left: 15px;
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
  margin-bottom: 5px;
}

.bio {
  font-size: 14px;
  color: #666;
}

.notes-list {
  max-height: 60vh;
  overflow-y: auto;
}

.note-list-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.note-thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.note-info {
  flex: 1;
  margin-left: 15px;
}

.note-info h4 {
  margin: 0 0 5px 0;
}

.note-info p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.note-actions {
  margin-left: 15px;
}

.likes-list {
  max-height: 60vh;
  overflow-y: auto;
}

.like-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.like-info {
  flex: 1;
  margin-left: 15px;
  display: flex;
  flex-direction: column;
}

.like-info .username {
  font-weight: bold;
}

.like-info .action {
  font-size: 14px;
  color: #666;
}

.like-info .note-title {
  font-size: 14px;
  color: #ff2442;
  margin-top: 5px;
}

.time {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .stats {
    gap: 15px;
  }
  
  .notes-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
  
  .tabs-container :deep(.el-tabs__item) {
    padding: 0 10px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .notes-grid {
    grid-template-columns: 1fr;
  }
  
  .profile-header {
    padding: 15px;
  }
  
  .name-row h2 {
    font-size: 20px;
  }
  
  .bio-tag {
    font-size: 14px;
  }
}

/* 公共样式 */
.note-item {
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
}

.note-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-container {
  position: relative;
  width: 100%;
  aspect-ratio: 1/1;
  background-color: #f5f5f5;
}

.note-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #ccc;
}

.image-error .el-icon {
  font-size: 40px;
}

 

.note-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.note-desc {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.note-tags {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.content-tag {
  background-color: #f5f5f5;
  border: none;
  color: #666;
  font-size: 12px;
  height: 24px;
  line-height: 22px;
}

/* 修改后的底部样式 */
/* .note-footer {
  padding: 8px 12px;
  border-top: 1px solid #f0f0f0;
} */

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-info .username {
  font-size: 12px;
  color: #666;
}

.like-action {
  display: flex;

  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

 

.like-action .el-icon {
  font-size: 16px;
  color: #ccc; /* 未点赞时的灰色轮廓 */
  stroke: currentColor;
  stroke-width: 2px;
  fill: transparent; /* 初始为透明填充 */
  transition: all 0.3s;
}

.like-action .el-icon.liked {
  color: #ff2442; /* 点赞后的红色 */
  fill: #ff2442; /* 实心填充 */
  stroke: #ff2442;
}

.like-count {
  font-size: 12px;
  color: #666;
}

/* 网格布局 */
.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  padding: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notes-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .notes-grid {
    grid-template-columns: 1fr;
  }
}

.note-image {
    position: relative;
    height: 0;
    padding-bottom: 133%;
    overflow: hidden;
  }
  
  .note-image img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>